package fm.dongman.animefm.view.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.*
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import fm.dongman.animefm.R
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.SheetListContract
import fm.dongman.animefm.view.activity.SingleActivity
import fm.dongman.animefm.view.adapter.UsedAdapter
import fm.dongman.animefm.view.listener.LoadMoreRecyclerOnScrollListener
import fm.dongman.animefm.view.transform.GlideRoundTransform
import fm.dongman.animefm.view.util.ActivityHelper
import fm.dongman.animefm.view.util.SystemHelper
import fm.dongman.animefm.view.util.ToastHelper
import fm.dongman.animefm.view.widget.MultiStateLayout
import fm.dongman.modellib.StaticArea.Injection
import fm.dongman.modellib.model.SheetModel
import fm.dongman.modellib.source.SheetListRepository
import fm.dongman.presenterlib.presenter.SheetListPresenter
import kotlinx.android.synthetic.main.fragment_sheet_list.*
import kotlinx.android.synthetic.main.header_sheet_list_special.view.*
import kotlinx.android.synthetic.main.item_sheet_list.view.*
import org.jetbrains.anko.onClick
import org.jetbrains.anko.onLongClick

/**
 * 漫单列表页面
 * Created by shize on 2017/11/5.
 */
class SheetListFragment : BaseFragment(), SheetListContract.ISheetListView {

    private var mPresenter: SheetListContract.ISheetListPresenter? = null // 全局数据控制器
    private var mFlagType: String = TYPE_SEARCH // 类型
    private var mFlagId: String? = null // 关键字 or id
    private var mNormalDialog:AlertDialog? = null // 是否删除的会话框
    private lateinit var mScrollListener: LoadMoreRecyclerOnScrollListener // 滑动监听器

    private lateinit var mSheetListAdapter: SheetListAdapter // 漫单列表适配器
    private val mSheetList: ArrayList<IModel.ISheetModel> = ArrayList() // 漫单数据集合
    lateinit var mDialog: Dialog
    private lateinit var mLlSpecialLayout: LinearLayout     //专题布局（作为header）
    private lateinit var mSheetListSpecialRecycler: RecyclerView    //专题列表
    private lateinit var mSheetListSpecialAdapter: SheetListSpecialAdapter // 专题列表适配器
    private val mSheetSpecialList: ArrayList<IModel.ISheetModel> = ArrayList() // 专题数据集合

    private lateinit var mFooterView: View // 列表底部 View

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val view = inflater!!.inflate(R.layout.fragment_sheet_list, container, false)
        SheetListPresenter(this, Injection.provideSheetListRepository())
        return view
    }

    override fun setNewParam(key: String) {
        mFlagId = key
        requestListData(1)
    }

    override fun requestListData(page: Int) {
        mPresenter?.getSheets(page, mFlagType, mFlagId)
        mScrollListener.clearPage()
        mSheetListAdapter.addFooterView(mFooterView)
        onStateChanged(MultiStateLayout.LOADING)
    }

    override fun initData() {
        if (arguments != null) {
            mFlagType = arguments.getString(FLAG_TYPE)
            if (mFlagId == null)
                mFlagId = arguments.getString(FLAG_ID)
        }
    }

    override fun bindData() {
        bindToolbar()
        bindSheetList()

        mDialog=Dialog(activity,R.style.progress_dialog)
        val view:View=View.inflate(activity,R.layout.layout_loading_dialog,null)
        val text: TextView = view.findViewById(R.id.mTvSaveImgDilog) as TextView
        text.text = "加载中...."
        mDialog.setContentView(view)
    }

    private fun bindToolbar() {
        mSheetListToolbar.setPadding(0, SystemHelper.getStatusBarHeight(activity), 0, 0)
        mSheetListToolbar.setNavigationOnClickListener {
            ActivityHelper.backActivity(activity)
        }
        // 分情况加载类型标题
        when (mFlagType) {
            TYPE_MANDAN -> mSheetListToolbar.title = getString(R.string.str_more_sheet)
            TYPE_SPEC -> mSheetListToolbar.title = getString(R.string.str_more_spec)
            TYPE_SEARCH -> mSheetListToolbar.visibility = View.GONE
            TYPE_USER_COL -> setUserTitle(getString(R.string.str_my_favorite))
            TYPE_USER_CREATE -> setUserTitle(getString(R.string.str_my_created))
            TYPE_USER_FOLLOW -> setUserTitle(getString(R.string.str_my_collection))
            else -> Toast.makeText(activity, getString(R.string.str_type_error), Toast.LENGTH_LONG).show()
        }
    }

    /**
     * 创建漫单
     */
    private fun createSheet() {
        val intent = Intent(activity, SingleActivity::class.java)
        intent.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_CREATE_OR_EDIT_SHEET)
        ActivityHelper.startActivity(activity, intent)
    }

    override fun showDeleteState(boolean: Boolean) {
        ToastHelper.getInstance(activity).showWarn("删除" + if (boolean) "成功" else "失败")
        mPresenter?.getSheets(1,mFlagType,mFlagId)
        mDialog.dismiss()
    }

    /**
     * 设置 Toolbar 的 Title
     * @param title 标题
     */
    private fun setUserTitle(title: String) {
        if (mFlagId != null) {
            mSheetListToolbar.visibility = View.GONE
            return
        }
        mSheetListToolbar.title = title
    }

    private fun bindSheetList() {
        mSheetListAdapter = SheetListAdapter(activity, mSheetList, mFlagType, TYPE_USER_COL)
        bindListHeaderFooter() // 绑定头部 View
        mSheetListRecycler.adapter = mSheetListAdapter
        mSheetListRecycler.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        mScrollListener = object : LoadMoreRecyclerOnScrollListener(mSheetListRecycler.layoutManager) {
            override fun onLoadMore(currentPage: Int) {
                mPresenter?.getSheets(currentPage, mFlagType, mFlagId)
            }
        }
        mSheetListRecycler.addOnScrollListener(mScrollListener)
        // 搜索直接启动 Fragment 没有经过 SingleActivity 的 onResume()
        if (mFlagType == TYPE_SEARCH) {
            requestListData(1)
        }
        // 用户详情也是直接启动 Fragment
        if((mFlagType == TYPE_USER_COL||mFlagType== TYPE_USER_FOLLOW)&& mFlagId!=null){
            requestListData(1)
        }

        if (mFlagType == TYPE_USER_CREATE) {
            mSheetListCreateMenuItem.visibility = View.VISIBLE
            mSheetListCreateMenuItem.onClick {
                createSheet()
            }
            mSheetListAdapter.setOnLongClickListener(object : SheetListAdapter.OnLongClickListener {
                override fun onLongClick(position: Int) {
                    showNormalDialog(position)
                    mNormalDialog?.show()
                }
            })
        }
    }

    private fun showNormalDialog(position: Int) {
        val mNormalDialogBuilder = AlertDialog.Builder(activity)
        mNormalDialogBuilder.setTitle("提示！")
        mNormalDialogBuilder.setMessage("删除漫单？")
        mNormalDialogBuilder.setPositiveButton("确定"
        ) { d, _ ->
            val sheet = mSheetList[position] as SheetModel
            mPresenter?.deleteSheet(sheet.mandanId)
            mDialog.show()
            d.dismiss()
        }
        mNormalDialogBuilder.setNegativeButton("关闭"
        ) { d, _ ->
            d.dismiss()
        }
        mNormalDialog = mNormalDialogBuilder.create()
    }

    @SuppressLint("InflateParams")
    private fun bindListHeaderFooter() {
        //初始化专题相关
        mLlSpecialLayout = View.inflate(activity, R.layout.header_sheet_list_special, null) as LinearLayout
        mSheetListSpecialRecycler = mLlSpecialLayout.mSheetListSpecialRecycler
        mSheetListSpecialAdapter = SheetListSpecialAdapter(activity, mSheetSpecialList)
        mSheetListSpecialRecycler.adapter = mSheetListSpecialAdapter
        mSheetListSpecialRecycler.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
        // 把整个专题布局包括列表 添加到漫单适配器的 addHeaderView 里
        if (mFlagType == TYPE_SEARCH)
            mSheetListAdapter.addHeaderView(mLlSpecialLayout)
        mFooterView = LayoutInflater.from(activity).inflate(R.layout.layout_loading, null)

    }

    override fun setPresenter(presenter: SheetListContract.ISheetListPresenter) {
        mPresenter = presenter
    }

    override fun showNoNetwork() {
        onStateChanged(MultiStateLayout.NET_ERROR)
    }

    override fun showRefreshFailed() {
        ToastHelper.getInstance(activity).showError(getString(R.string.str_refresh_failed))
        onStateChanged(MultiStateLayout.EMPTY)
    }

    override fun showSheets(sheets: List<IModel.ISheetModel>) {
        onStateChanged(MultiStateLayout.SUCCESS)
        mSheetList.clear()
        mSheetList.addAll(sheets)
        mSheetListAdapter.notifyDataSetChanged()
        if (sheets.size < 10) {
            // 加载完毕
            mSheetListAdapter.removeFooterView()
        }
    }

    override fun showMoreSheets(sheets: List<IModel.ISheetModel>) {
        if (sheets.isEmpty()) {
            mSheetListAdapter.removeFooterView()
            return
        }
        mSheetList.addAll(sheets)
        mSheetListAdapter.notifyDataSetChanged()
    }

    override fun showSearchTopicResult(topics: List<IModel.ISheetModel>) {
        // 显示搜索的专题结果
        mSheetSpecialList.clear()
        mSheetSpecialList.addAll(topics)
        mSheetListSpecialAdapter.notifyDataSetChanged()
    }

    override fun showMoreSearchTopicResult(topics: List<IModel.ISheetModel>) {
        // 显示更多搜索的专题结果
        mSheetSpecialList.addAll(topics)
        mSheetListSpecialAdapter.notifyDataSetChanged()
    }

    override fun isActive(): Boolean = isAdded

    override fun getViewContext(): Context = activity

    /**
     * 切换状态
     */
    private fun onStateChanged(state: Int) {
        mSheetListMultiState?.changeState(state)
    }

    companion object {
        private val FLAG_TYPE = "fm.dongman.animefm.sheetList.flagType" // 类型 key
        private val FLAG_ID = "fm.dongman.animefm.sheetList.flagId" // id key

        val TYPE_SEARCH = SheetListContract.ISheetListPresenter.TYPE_SEARCH // 搜索
        val TYPE_SPEC = SheetListRepository.SPEC // 专题
        val TYPE_MANDAN = SheetListRepository.MANDAN // 漫单
        val TYPE_USER_FOLLOW = SheetListRepository.USER_FOLLOW // 用户关注的漫单
        val TYPE_USER_CREATE = SheetListRepository.USER_CREATE // 用户创建的漫单
        val TYPE_USER_COL = SheetListRepository.USER_COL // 用户收藏的专题

        /**
         * 获取实例
         */
        fun getInstance(flagType: String, flagId: String?): SheetListFragment {
            val bundle = Bundle()
            bundle.putString(FLAG_TYPE, flagType)
            bundle.putString(FLAG_ID, flagId)
            val fragment = SheetListFragment()
            fragment.arguments = bundle
            return fragment
        }
    }

    /**
     * 漫单列表适配器
     */
    private class SheetListAdapter(private val mContext: Context, private val mData: List<IModel.ISheetModel>, val mFlagTyp: String, val mMyType: String)
        : UsedAdapter<SheetListAdapter.SheetListViewHolder>() {
        private var mLongListener: OnLongClickListener? = null // 长按监听器

        @SuppressLint("InflateParams")
        override fun onCreateVH(): SheetListViewHolder =
                SheetListViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_sheet_list, null))

        override fun onBindVH(holder: SheetListViewHolder, position: Int) {
            val sheet = mData[position] as SheetModel
            holder.mDate.text = sheet.createTime

            holder.itemView.onClick {
                if (mFlagTyp == mMyType) {
                    val intent = Intent(mContext, SingleActivity::class.java)
                    intent.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_SPECIAL_INFO)
                    intent.putExtra(SingleActivity.BUNDLE_EXTRA_KEY_ID, sheet.mandanId)
                    ActivityHelper.startActivity(mContext as Activity, intent)
                } else {
                    val intent = Intent(mContext, SingleActivity::class.java)
                    intent.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_SHEET_INFO)
                    intent.putExtra(SingleActivity.BUNDLE_EXTRA_KEY_ID, sheet.mandanId)
                    ActivityHelper.startActivity(mContext as Activity, intent)
                }
            }
            // 长按事件监听器
            holder.itemView.onLongClick {
                if (mLongListener == null) {
                    return@onLongClick false
                }
                mLongListener!!.onLongClick(holder.adapterPosition)
                return@onLongClick true
            }

            holder.mTitle.text = sheet.mandanTitle
            Glide.with(mContext).load(sheet.mandanImg)
                    .bitmapTransform(CenterCrop(mContext), GlideRoundTransform(mContext, 2))
                    .into(holder.mCover)
        }

        override fun getDataTotal(): Int = mData.size

        /**
         * 长按监听器
         */
        fun setOnLongClickListener(listener: OnLongClickListener) {
            mLongListener = listener
        }

        private class SheetListViewHolder(itemView: View) : UsedAdapter.UsedViewHolder(itemView) {
            var mTitle: TextView = itemView.mTvSheetListTitle
            var mDate: TextView = itemView.mTvSheetListDate
            var mCover: ImageView = itemView.mIvSheetListCover
        }

        interface OnLongClickListener {
            /**
             * 长按
             * @param position 位置
             */
            fun onLongClick(position: Int)
        }
    }

    /**
     * 漫单列表适配器(专题)
     * 动漫详情 相关专题 也使用此适配器
     */
    class SheetListSpecialAdapter constructor(private val mContext: Context, private val mData: List<IModel.ISheetModel>)
        : RecyclerView.Adapter<SheetListSpecialAdapter.SheetListViewHolder>() {

        @SuppressLint("InflateParams")
        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): SheetListViewHolder =
                SheetListViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_sheet_list_special, null))

        override fun onBindViewHolder(holder: SheetListViewHolder?, position: Int) {
            val sheet = mData[position] as SheetModel
            holder!!.mDate.text = sheet.createTime

            holder.itemView.onClick {
                val intent = Intent(mContext, SingleActivity::class.java)
                intent.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_SPECIAL_INFO)
                intent.putExtra(SingleActivity.BUNDLE_EXTRA_KEY_ID, sheet.mandanId)
                ActivityHelper.startActivity(mContext as Activity, intent)
            }

            holder.mTitle.text = sheet.mandanTitle
            Glide.with(mContext).load(sheet.mandanImg)
                    .into(holder.mCover)
        }

        override fun getItemCount(): Int = mData.size

        class SheetListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val mTitle: TextView = itemView.mTvSheetListTitle
            val mDate: TextView = itemView.mTvSheetListDate
            val mCover: ImageView = itemView.mIvSheetListCover
        }
    }
}